package com.kzw.tools;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

/**
 * Mapping文件：
 * 		MySQL ==> Oracle (修改主键生成策略)
 * */
public class HbmMySQL2Oracle {

	private static List<String> sequences = new ArrayList<String>();
	
	/**
	 * 递归扫描某目录及子目录下的.hbm.xml文件
	 * */
	public static void addSequence(File file) throws Exception {
		if(file.getName().equals("web") || file.getName().startsWith(".")) return;
		
		if(file.isFile()) {
			String fname = file.getName();
			if(fname.endsWith(".hbm.xml")) {
				String content = FileUtils.readFileToString(file, "UTF-8");
				String entityName = StringUtils.substringBefore(content, ".hbm.xml");
				entityName = "S" + entityName.replaceAll("([A-Z])", "_$1").toUpperCase();
				
				String generator = "<generator class=\"sequence\"><param name=\"sequence\">"+entityName+"</param></generator>";
				String newContent = content.replaceAll("<generator class=\"native\".*?/>", generator);
				if(!newContent.equals(content)) {
					System.out.println(file.getCanonicalPath());
					FileUtils.writeStringToFile(file, newContent, "UTF-8");
				}
				sequences.add(entityName);
			}
		} else {
			File[] fs = file.listFiles();
			for(File f : fs) {
				addSequence(f);
			}
		}
	}
	
	/**
	 * 生成Oracle序列的SQL语句
	 * */
	public static void genSequenceSQL() {
		for(String seq : sequences) {
			String sql = "CREATE SEQUENCE "+seq+" INCREMENT BY 1 START WITH 10000 NOMAXVALUE MINVALUE 1 CACHE 20 NOORDER NOCYCLE;";
			System.out.println(sql);
		}
	}
	
	public static void main(String[] args) throws Exception {
		String path = HbmMySQL2Oracle.class.getResource("/").toURI().getPath();
		File srcPath = new File(path, "../../../").getCanonicalFile();
		System.out.println("处理根路径：" + srcPath.getCanonicalPath());
		
		addSequence(srcPath);
	}
}
